#include "qcomboitemeditor.h"

#include "qcomboitemeditdialog.h"
#include "../undocommand/qpropertychangedundocommand.h"
#include "../undocommand/qresourceaddundocommand.h"
#include "../qsoftcore.h"
#include "../qfilemanager.h"

#include "../../shared/property/qabstractproperty.h"
#include "../../shared/host/qabstracthost.h"
#include "../../shared/qcommonstruct.h"
#include "../../shared/qprojectcore.h"
#include "../../shared/resource/qresourcemanager.h"
#include "../../shared/resource/qresourcefile.h"
#include "../../shared/qpropertyfactory.h"

QComboItemEditor::QComboItemEditor(QAbstractProperty *property,QUndoStack* stack, QWidget *parent):
    QButtonCommonEditor(property,stack,parent),
    m_undo_stack(stack)
{
}

void QComboItemEditor::btn_clicked()
{
    QComboItemEditDialog dlg(m_property->get_value(),this);

    dlg.exec();

    if(dlg.get_ret()==1)
    {
        QVariant v=dlg.get_value();
        if(!m_property->cmp(v))
        {
            QUndoCommand *cmd=new QUndoCommand;
            ComboBoxItems items1=m_property->get_value().value<ComboBoxItems>();
            ComboBoxItems items2=v.value<ComboBoxItems>();

            QResourceFile *f=QSoftCore::get_core()->get_project_core()->get_resource_manager()->get_file();

            for(int i=0;i<items2.size();i++)
            {
                if(i<items1.size() && items2.at(i).m_icon==items1.at(i).m_icon)
                {
                    continue;
                }
                tagResourceInfo *info=f->resource(items2.at(i).m_icon);
                if(info!=NULL)
                {
                    new QResourceAddUndoCommand(info->m_resourceData,info->m_resourceName,RAT_ADD,cmd);
                }
            }

            new QPropertyChangedUndoCommand(m_property->get_host()->get_uuid(),
                                            m_property->get_name(),
                                            m_property->get_value(),
                                            v,cmd);

            for(int i=0;i<items1.size();i++)
            {
                if(i<items2.size() && items2.at(i).m_icon==items1.at(i).m_icon)
                {
                    continue;
                }
                tagResourceInfo *info=f->resource(items1.at(i).m_icon);
                if(info!=NULL)
                {
                    new QResourceAddUndoCommand(info->m_resourceData,info->m_resourceName,RAT_REMOVE,cmd);
                }
            }

            m_undo_stack->push(cmd);
        }
    }
}

qRegisterPropertyEditor(ComboItem,QComboItemEditor)
